var udpModule = require('nl.icept.network.udp');

var udpSocket = null;

var startButton = Ti.UI.createButton({
	height: '100px',
	left: '20px',
	right: '20px',
	
	title: 'Start Server'
});

var stopButton = Ti.UI.createButton({
	height: '100px',
	left: '20px',
	right: '20px',
	
	title: 'Stop Server'
});

Ti.UI.currentWindow.add(startButton);

startButton.addEventListener('click', function() {
	udpSocket = udpModule.createUDPSocket({
		port: 12345
	});
	
	(function waitForClientPacket() {
		if (udpSocket != null) {
			if (udpSocket.isReadable()) {
				udpSocket.read(function(packet) {
					udpSocket.write(packet.ip, packet.port, "Hey Client, i received from you: " + packet.data);
				});
			}
			
			setTimeout(waitForClientPacket, 1000);
		}
	})();
	
	serverInfoLabel.text = 'Listening on ' + Ti.Platform.address + ':12345';
	
	Ti.UI.currentWindow.remove(startButton);
	Ti.UI.currentWindow.add(stopButton);
});

stopButton.addEventListener('click', function() {
	udpSocket.close();
	udpSocket = null;
	
	serverInfoLabel.text = '';
	
	Ti.UI.currentWindow.remove(stopButton);
	Ti.UI.currentWindow.add(startButton);
});

var serverInfoLabel = Ti.UI.createLabel({
	height: '100px',
	bottom: '20px',
	
	textAlign: 'center',
});

Ti.UI.currentWindow.add(serverInfoLabel);